package 力扣;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhuYi
 * @create 2025/4/7 10:39
 */
public class 全排列无重复_46 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        System.out.println(permute(nums).toString());
    }

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
        return res;
    }

    static void backtrack(List<Integer> state, int[] nums, boolean[] selected, List<List<Integer>> res) {
        if (state.size() == nums.length) {
            res.add(new ArrayList<>(state));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            //剪枝：不允许重复选择元素
            if (!selected[i]) {
                //尝试
                state.add(num);
                selected[i] = true;
                //下一轮选择
                backtrack(state, nums, selected, res);
                //回溯
                selected[i] = false;
                state.remove(state.size() - 1);
            }
        }
    }
}
